<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits, watch, toRaw } from 'vue'
import { getApi, inWarehouseApi } from '/@/api/mes/finishe-product'
import { useInModal } from '/@/hooks/useModal'
import { useInsertSucessMessage, useSuccessMessage, useUpdateSucessMessage } from '/@/hooks/useMessage'
import { dataFormatter } from '/@/utils/data'
import dayjs from 'dayjs'

const props = defineProps(({
  ids: String
}))

const emits = defineEmits(['change'])

const modal = useInModal()

const formRef = ref<FormMakerInstance>()
const formProps = reactive<FormMakerProps>({
  name: 'productForm',
  model: {
    warehouseId: '',
    handler: '',
    circulateDate: dayjs().format('YYYY-MM-DD')
  },
  options: [
    {
      field: "warehouseId", label: "仓库", required: true,
      component: {
        key: 'SelectMaker',
        props: {
          dataSource: 'Warehouse'
        }
      }
    },
    {
      field: "handler", label: "经手人", required: true,
      component: {
        key: 'SelectMaker',
        props: {
          dataSource: 'Employee'
        }
      }
    },
    { field: "circulateDate", label: "入库日期", required: true, component: 'ElDatePicker' },
  ]
})

const tableRef = ref<YTableInstance>()
const tableProps = reactive<YTableProps>({
  height: "auto",
  columns: [
    { field: "workOrderCode", label: "工单编号" },
    { field: "productName", label: "产品名称" },
    { field: "productCode", label: "产品编号" },
    { field: "productUnit", label: "单位" },
    { field: "productCalcUnit", label: "计量单位", edit: true },
    { field: "quantity", label: "数量" },
    { field: "calcQuantity", label: "计量", edit: true },
    { field: "remark", label: "备注", edit: true },
  ],
  editOperas: ['add', 'delete', 'fill'],
  config: {
    edit: true
  }
});

watch(() => props.ids, (ids: string) => {
  if (ids) {
    modal.loading(true)
    getApi(ids)
      .then(res => {
        Object.assign(formProps.model, res.data)
        tableRef.value.loadData(res.data.items)
      })
      .finally(() => modal.loading(false))
  }
}, { immediate: true })

const viewLayout: ViewLayoutProps = {
  buttons: [
    {
      title: '确定', type: 'primary', onClick: async (title) => {
        await formRef.value.validate()
        await modal.loadingWarp(async () => {
          const { succeeded } = await inWarehouseApi({
            ...formProps.model,
            items: tableRef.value.getData()
          })

          if (succeeded) {
            emits('change')
            useSuccessMessage(title + '成功')
          }

        })
      }
    },
    { title: '取消', onClick: () => modal.close() },
  ]
}



</script>

<template>
  <ViewLayout v-bind="viewLayout">
    <template #header>
      <FormMaker v-bind="formProps" ref="formRef" />
    </template>
    <YTable v-bind="tableProps" ref="tableRef"></YTable>
  </ViewLayout>
</template>